package tool

import (
	"fmt"
	"strings"
	"time"
)

func Brute(ip string) {
	fmt.Println("主机暴力破解开始")

	hostSshExpect := `#!/usr/bin/expect                                                                                                                            

for {set j 0} {${j}<60} {incr j} {
    spawn ssh derek${j}@` + ip + `
    expect {
        "yes/no" { send "yes\n"; exp_continue }
        "password:" { send "123456\n" }
    }
}`
	filePath := "./data/expect.sh"
	//file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 06666)
	//if err != nil {
	//	fmt.Println("打开文件错误= &v \n", err)
	//	return
	//}
	//defer file.Close()
	////写入内容
	//writer := bufio.NewWriter(file)
	//writer.WriteString(hostSshExpect)
	//writer.Flush()
	WriterFile(filePath, hostSshExpect)
	RunInLinux("chmod +x " + filePath)
	RunInLinux("yum install -y expect")
	fmt.Println(RunInLinux(filePath))

	fmt.Println("容器暴力破解")

	ContainerSshExpect := `#!/usr/bin/expect                                                                                                                            

for {set j 0} {${j}<60} {incr j} {
    spawn ssh derek${j}@127.0.0.1 -p 2222
    expect {
        "yes/no" { send "yes\n"; exp_continue }
        "Password:" { send "123456\n" }
    }
}`

	ContainerSshPath := "./data/ContainerExpect.sh"
	WriterFile(ContainerSshPath, ContainerSshExpect)

	containeryaml := `version: "2.1"
services:
  openssh-server:
    image: lscr.io/linuxserver/openssh-server
    container_name: openssh-server
    hostname: openssh-server #optional
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Asia/Shanghai
      - PASSWORD_ACCESS=true
      - USER_PASSWORD=test123
      - USER_NAME=derek
    volumes:
      - /tmp/sshd:/config
    ports:
      - 2222:2222
    restart: unless-stopped`

	containeryamlpath := "./docker-compose.sh"
	WriterFile(containeryamlpath, containeryaml)

	fmt.Println(RunInLinux("docker-compose up -d"))

	time.Sleep(10 * time.Second)
	RunInLinux("chmod +x " + ContainerSshPath)
	fmt.Println(RunInLinux(ContainerSshPath))

	output := RunInLinux("docker ps | grep openssh-server")
	GlobalObject.SshContainerId = strings.Split(output, "  ")[0]
	fmt.Println(GlobalObject.SshContainerId)
}
